<template>
  <!-- 最大盒子 -->
  <s-layout :tabbarshow="false" id="layout" navbar="normal" :title="'我的代理'" :autoBack="true" leftIconColor="$uni-text-color"
      :bgColor="'#ffffff'" :titleStyle="{ color: '$uni-text-color', fontSize: '32rpx', fontWeight: '600' }" :onShareAppMessage="shareInfo">
      <!-- 最大盒子 -->
      <view class="max_box" :style="{ paddingTop: (safeAreaInsets?.top + 44) + 'px' }">
          <!-- 搜索 && 是否结算 盒子 -->
          <view class="top_box">
              <!-- 搜索组件 -->
              <view class="area search_box">
                  <s-search-keyword :border="'1px solid rgba(0, 56, 247, 0.3)'" :placeholder="'搜索员工'"
                      @searchKeyWord="searchKeyWord"></s-search-keyword>
              </view>
              <!-- 空白盒子 -->
              <view class="blank_box" @tap="remove">
                <view class="remove">
                  <image :src="`${baseUrl}/uploads/uniapp_image/staff/wodedaili_icon_yichudaili.png`"
                                  mode="scaleToFill"  />
                  <view class="name">移除代理</view>
                </view>
              </view>
              <!-- 列表 -->
              <view class="wraps">
                  <scroll-view  @scrolltolower='listScrolltolower' scroll-y class="scroll_box " v-if="list.length" :style="fit == true?'height:60vh':'height:74vh'"
                  show-scrollbar="true"
                  :refresher-enabled="isOpenRefresh"
                  :refresher-triggered="triggered"
                  :refresher-threshold="100"
                  refresher-background="white"
                  @refresherpulling="onPulling"
                  @refresherrefresh="onRefresh"
                  @refresherrestore="onRestore"
                  @refresherabort="onAbort"
                  @scroll="onScroll"
                  >
                      <view v-for="i in list" :key="i.id">
                          <view class="list_item_title">
                            <view>
                              <image :src="`${baseUrl}/uploads/uniapp_image/staff/wodedaili_icon_project.png`"
                                  mode="scaleToFill" v-if="i.source == 1" />
                              <image :src="`${baseUrl}/uploads/uniapp_image/user/bancidetails_icons_dailiren.png`"
                                  mode="scaleToFill" v-else />
                              <view class="titlename">{{ i.company.name }} / {{ i.name }}</view>
                            </view>
                            <view class="add_right">
                              <view @tap="agentWanted(i)">
                                <text class="orange">招募代理</text>
                              </view>
                              <!-- <view class="hint"></view> -->
                            </view>
                              
                          </view>

                          <view class="list_item" v-for="(item, index) in i.list" :key="index"  @tap="moreSelect(item.id)" >
                            <view class="Left_box">
                              <!-- 选择按钮 -->
                              <view class="select_image" v-if="fit == true ">
                                  <image v-if="isSelected(item.id)"
                                      :src="`${baseUrl}/uploads/uniapp_image/staff/kehuguanli_icon_check.png`"
                                      mode="scaleToFill" />
                                  <image v-else
                                      :src="`${baseUrl}/uploads/uniapp_image/staff/kehuguanli_icon_checkfor.png`"
                                      mode="scaleToFill" />
                              </view>
                              <!-- 头像 -->
                              <view class="head_box">
                                  <image :src="`${baseUrl}` + item.user.avatar" mode="aspectFill" />
                              </view>
                              <!-- 信息盒子 -->
                              <view class="message_box">
                                  <view class="message_title">{{ item.user.nickname }}</view>
                                  <view class="message_identity">{{ item.user.authentication.identity_id }} {{ item.user.gender == 0 ? '女' : '男' }}</view>
                                  <view class="mes_flex">
                                      <view class="message_time" @tap="callphone(item.user.mobile)">
                                        <image
                                          :src="`${baseUrl}/uploads/uniapp_image/staff/kehuguanli_icon_callnumber.png`"
                                          mode="scaleToFill"
                                          v-if="`${baseUrl}/uploads/uniapp_image/staff/kehuguanli_icon_callnumber.png`"
                                        />
                                          <text>
                                            电话：{{ item.user.mobile}}
                                          </text>
                                          
                                      </view>
                                  </view>
                              </view>
                            </view>
                              
                            <view class="list_item_title_right" @tap="lookDetails(i,item)">
                              <text>详情</text>
                              <u-icon size="10" name="arrow-right" color="#0038F7"></u-icon>
                            </view>
                          </view>
                      </view>
                        <!-- 正在加载组件 -->
                      <view>
                        <s-loadmore-gather :current_page="listPage" :last_page="listlast_page" ref="loadmoreRef"></s-loadmore-gather>
                      </view>
                  </scroll-view>
                  <u-empty v-else mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png" text="暂无内容"></u-empty>
              </view>
          </view>


          <!-- 底部占位盒子 -->
          <view class="end_box"  v-if="fit == true ">
              <!-- 全选按钮盒子 -->
              <view class="check_all_box">
                  <!-- 全选按钮 -->
                  <view class="check_all_button" @tap="checkAllInteraction">
                      <view class="select_image">
                          <image v-show="checkAll == 1"
                              :src="`${baseUrl}/uploads/uniapp_image/staff/kehuguanli_icon_check.png`"
                              mode="scaleToFill" />
                          <image v-show="checkAll == 0"
                              :src="`${baseUrl}/uploads/uniapp_image/staff/kehuguanli_icon_checkfor.png`"
                              mode="scaleToFill" />
                      </view>
                      <view>全选</view>
                  </view>
                  <!-- 已选择 -->
                  <view class="selected_box">
                      <view class="number_people">已选择 {{ selectedIds.length }}/{{ personLength }} 个项目</view>
                  </view>
              </view>
              <view class="placeholder"></view>
                <!-- 底部按钮 -->
              <s-button @leftNetWork="leftTrigger" @rightNetWork="rightTrigger"  :leftWidth="'50%'" :rightWidth="'50%'" :type="'twobutton'" :oneText="'取消'" :twoText="'移除代理'" ></s-button>
          </view>
      </view>
    

  </s-layout>
</template>
<script setup>
import { baseUrl } from '@/sheep/config';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { reactive, ref,computed } from "vue";
import { showShareModal } from '@/sheep/hooks/useModal';
import tools from '@/sheep/helper/tools.js';
import sheep from "@/sheep";
// 获取系统信息
const { safeAreaInsets } = uni.getSystemInfoSync();
const PopupId = ref()
const date = ref()
const schedule_id =ref()
onLoad((options) => {
  PopupId.value = options.user_id
  date.value = options.date
  schedule_id.value =options.schedule_id
  personLength.value = Number(0)
   getIndex()
});

//移除按钮显示隐藏
const fit = ref(false)
const remove = ()=>{
  fit.value =true
}
//打电话
const callphone = (e)=>{
  tools.callPhone(e)
}
// 多选  total.value 总共多少条数据
const moreSelect = (id) => {
  const index = selectedIds.value.indexOf(id);
  if (index === -1) {
      selectedIds.value.push(id);
      if (selectedIds.value.length == allList.value.length) {
          checkAll.value = 1
      }
  } else {
      selectedIds.value.splice(index, 1);
      if (selectedIds.value.length !== allList.value.length) {
          checkAll.value = 0
      }
  }
}
const isSelected = (id) => {
return selectedIds.value.includes(id);
}
// 全选
const checkAll = ref(0)
const selectedIds = ref([])
// 全选交互逻辑
const checkAllInteraction = () => {
  if (checkAll.value === 0) {
      selectedIds.value = allList.value.map(item => item.id);
      checkAll.value = 1;
  } else {
      selectedIds.value = [];
      checkAll.value = 0;
  }
}
//搜索
const keyword = ref()
const searchKeyWord = (srarch_value) => {
  list.value = []
  listpagenumber.value = 1
  allList.value = []
  selectedIds.value = []
  checkAll.value = 0
  fit.value = false
  keyword.value = srarch_value
  personLength.value = Number(0)
  getIndex()
}
//请求数据
//人员列表
const personLength = ref(Number(0))
const list = ref([])//代理上列表
const listPage = ref()
const listlast_page = ref();
const listpagenumber = ref(1);
const allList = ref([])
const getIndex = async () => {
  let params = {
     page: listpagenumber.value,
     filter: JSON.stringify({
            'user.nickname': keyword.value,
        }),
        op: JSON.stringify({
            'user.nickname': 'LIKE',
        }),
  }
  const res = await sheep.$api.agency.my_children_listAPI(params);
  if (res.code == 1 ) {
    list.value = [...list.value, ...res?.data.rows];
    listPage.value = res.data.current_page
		listlast_page.value = res.data.last_page
    list.value.forEach(items => {
      allList.value = [...allList.value, ...items.list];
    })
    allList.value = [...new Set(allList.value)]
     // 点击全选 塞值
     if(checkAll.value == 1) {
      if(list.value.length !== 0) {  
        res.data.rows.forEach(item => {
          item.list.forEach(c => {
            selectedIds.value.push(c.id)
          })
        })
      }
    }
    personLength.value =  res.data.total;
  }
}

  //滚动触底
  const loadmoreRef = ref()
  const listScrolltolower = () => {
    loadmoreRef.value.PopupScrolltolower()
          if (listPage.value < listlast_page.value) {
          listpagenumber.value += 1;
            
        } else {
           return;
          }
          getIndex();
    };
// 移除代理
const rightTrigger = async()=>{
  // 移除代理
  if(selectedIds.value.length !== 0 || checkAll.value == 1){
    let params = {
      ids:selectedIds.value.join(',')
    }
    const res = await sheep.$api.agency.postuser_agentDelAPI(params);
    if(res.code == 1){
      sheep.$helper.toast(res.msg);
      selectedIds.value = []
      checkAll.value = 0
      allList.value = []
      list.value =[]
          setTimeout(() => {
            listpagenumber.value = 1
            getIndex()
          }, 500)
    }else{
      sheep.$helper.toast(res.msg);
    }
  }else{
      sheep.$helper.toast('请选择员工,再进行操作');
  }
}
//取消
const leftTrigger =()=>{
  fit.value = false 
  selectedIds.value =[]
  listpagenumber.value = 1
  
  checkAll.value = 0;
}

//查看项目
const lookDetails = (i,item)=>{
  // let itemobj = i.list[0].department_id;
  sheep.$router.go('/subpackage/user/user/my_agent/my_agent_details',{
    department_id:i.id,
    title:i.company.name + ' / ' + i.name,
    user_id:item.user_id,
    name:item.user.nickname,
    head:item.user.avatar
    })
}
//招募代理//分享招人
const share =ref({
  id:'',
  project_name:''
})
const agentWanted = async(item) =>{
  share.value.id = item.id
  share.value.project_name = item.name
  showShareModal();
}
const shareInfo = computed(() => {
  return sheep.$platform.share.getShareInfo(
    {
      title: share.value.project_name,
      desc: '暂无数据',
      params: {
        page: '4',
        query:share.value.id,
        title: share.value.project_name,
      },
    },
    {
      type: 'agency', // 邀请代理海报
      title:share.value.project_name
    },
  );
});
  // 页面下拉刷新
  const freshing = ref(false)
const triggered = ref(false)
const isOpenRefresh = ref(true)  // 是否开启下拉
// 自定义下拉刷新控件被下拉
const onPulling=(e)=> {
  if (e.detail.deltaY < 0) return  // 防止上滑页面也触发下拉
  triggered.value= true;
}
// 自定义下拉刷新被触发
const onRefresh=()=>  {
  if (freshing.value) return;
  freshing.value= true;
  setTimeout(() => {
    triggered.value= false;
    freshing.value= false;
    list.value = []
  listpagenumber.value = 1
  allList.value = []
  selectedIds.value = []
  checkAll.value = 0
  fit.value = false

  personLength.value = Number(0)
  getIndex()
  }, 500);
}
// 自定义下拉刷新被复位
const onRestore=()=> {
  triggered.value= 'restore'; // 需要重置
  // console.log("onRestore");
}
// 自定义下拉刷新被中止
const onAbort=()=>  {
  // console.log("onAbort");
}
</script>

<style scoped lang="scss">
page {
  width: 100%;
  height: 100%;
}

// 版心
.area {
  width: calc(100% - 40rpx);
  margin: 0 20rpx;
}

:deep(.u-form-item__body.data-v-b4fd400b) {
  padding: 20rpx 0 20rpx 30rpx;
}

:deep(.u-form-item__body__left__content__label.data-v-b4fd400b) {
  font-weight: $uni-font-weight;
}

:deep(.u-form-item__body__right__message.data-v-b4fd400b) {
  margin-left: 200rpx !important;
}

// 头部盒子
.top_box {
  height: 80rpx;
  background-color: #ffffff;
  padding: 20rpx 0;
}

// 空白盒子
.blank_box {
  height: 120rpx;
  .remove{
    height: 80rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    background: $uni-bg-color;
    margin: 20rpx 0;
    border-top: 20rpx solid #F4F6FA;
  }
  image{
    width: 30rpx;
    height: 30rpx;
    margin-right: 10rpx;
  }
  .name{
    color: $uni-color-primary;
  font-weight: 500;
  font-size: $uni-font-size-base;
  }
}

// 列表
.scroll_box {
  height: 60vh;
  border-radius: 16rpx;
  background-color: #FFFFFF;
  box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.05);
}

// 列表项
.list_item {
  height: 154rpx;
  display: flex;
  align-items: center;
  margin: 0 30rpx 40rpx 30rpx;
  position: relative;
  justify-content: space-between;
  .Left_box {
    display: flex;
    align-items: center;
  }

  // border-bottom: 2rpx solid #efefef;
  // 选择图标
  .select_image {
      width: 30rpx;
      height: 30rpx;
      margin-right: 22rpx;

      image {
          width: 100%;
          height: 100%;
      }
  }

  // 头像盒子
  .head_box {
      width: 104rpx;
      height: 104rpx;

      image {
          width: 100%;
          height: 100%;
          border-radius: 50%;
      }
  }

  // 信息盒子
  .message_box {
      margin-left: 30rpx;

      .message_title {
          font-family: PingFangSC;
          color: $uni-text-color;
          font-weight: $uni-font-weight;
          font-size: 30rpx;
          font-style: normal;
          text-decoration: none;
          margin-bottom: 4rpx;
      }

      .message_identity {
          font-family: PingFangSC;
          color: #999999;
          font-weight: 400;
          font-size: $uni-font-size-sm;
          font-style: normal;
          text-decoration: none;
          margin-bottom: 10rpx;
      }

      .message_time {
          font-family: PingFangSC;
          color: $uni-text-color;
          font-weight: 500;
          font-size: $uni-font-size-sm;
          font-style: normal;
          text-decoration: none;
          display: flex;
          align-items: center;
          image{
            width: 38rpx;
            height: 38rpx;
          }
          text {
              display: block;
              margin-left: 10rpx;
              color: $uni-color-primary;
              font-weight: 400;
              font-size: 22rpx;
          }
      }
  }
}

.list_item:first-child {
  border-top-left-radius: 16rpx;
  border-top-right-radius: 16rpx;
  margin-top: 30rpx;
}

.list_item:last-child {
  border-bottom-left-radius: 16rpx;
  border-bottom-right-radius: 16rpx;
  margin-bottom: 0;
}





// 底部占位盒
.placeholder_bottom {
  height: 220rpx;
  width: 100%;
  margin-top: 20rpx;
}

// 末尾盒子 (此盒子没有  “父相 ” 如要改动请按需更改)
.end_box {
  position: fixed;
  bottom: 0;
  height: 244rpx;
  width: 100%;

  // 全选按钮盒子
  .check_all_box {
      height: 80rpx;
      width: 100%;
      background-color: #ffffff;
      display: flex;
      justify-content: space-between;
      border: 2rpx solid #efefef;

      // 全选按钮
      .check_all_button {
          display: flex;
          margin-left: 52rpx;
          align-items: center;
          font-family: PingFangSC;
          color: #0239f7;
          font-weight: $uni-font-weight;
          font-size: $uni-font-size-base;
          font-style: normal;
          text-decoration: none;
      }

      // 已选择
      .selected_box {
          display: flex;
          margin-right: 40rpx;
          align-items: center;
          font-family: PingFangSC;
          color: $uni-text-color;
          font-weight: $uni-font-weight;
          font-size: $uni-font-size-base;
          font-style: normal;
          text-decoration: none;
      }
  }

  // 占位盒子
  .placeholder {
      height: 32rpx;
      width: 100%;
      background-color: #ffffff;
  }
}

// 全选图标
.select_image {
  width: 30rpx;
  height: 30rpx;
  margin-right: 22rpx;

  image {
      width: 100%;
      height: 100%;
  }
}
// 执照员工代理商
.list_item_title {
  padding:0 30rpx;
  height: 60rpx;
  margin-top: 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .add_right{
    display: flex;
    align-items: center;
    .hint{
      margin: 0 18rpx;
      color: #cecece;
      height: 23rpx;
      width: 3rpx;
      background: #cecece;
    }
  }
  view{
    display: flex;
  }
  image {
      width: 30rpx;
      height: 30rpx;
  }

  .titlename {
      color: $uni-text-color;
      font-weight: 500;
     font-size:$uni-font-size-26;
      margin-left: 20rpx;
  }
  
    
    .orange{
      display: flex;
      font-weight: 500;
      font-size: 22rpx;
      color: #FF6600;
    }
}
.list_item_title_right{
  color: $uni-color-primary;
  font-weight: 500;
  font-size: 22rpx;
}
.wraps{
  width: calc(100% - 40rpx);
  margin: 0 auto;
}
</style>